package com.system.util;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Logger;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import com.alibaba.fastjson.JSONObject;

@SuppressWarnings("unchecked")
public class GzipUtils {
	public static String TAG = GzipUtils.class.getName();
	public static Logger logger = Logger.getLogger(TAG);

	public static byte[] gzip(byte[] bArr) {
		try {
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(bArr.length);
			GZIPOutputStream gZIPOutputStream = new GZIPOutputStream(byteArrayOutputStream);
			gZIPOutputStream.write(bArr);
			gZIPOutputStream.close();
			byteArrayOutputStream.close();
			return byteArrayOutputStream.toByteArray();
		} catch (IOException unused) {
			logger.warning("GzipUtils: failed to gzip");
			return bArr;
		}
	}

	public static byte[] ungzip(byte[] bArr) {
		try {
			ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bArr);
			GZIPInputStream gZIPInputStream = new GZIPInputStream(byteArrayInputStream);
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(gZIPInputStream, StandardCharsets.UTF_8));
			StringBuilder sb2 = new StringBuilder();
			while (true) {
				String readLine = bufferedReader.readLine();
				if (readLine != null) {
					sb2.append(readLine);
				} else {
					bufferedReader.close();
					gZIPInputStream.close();
					byteArrayInputStream.close();
					return sb2.toString().getBytes();
				}
			}
		} catch (IOException unused) {
			logger.warning("GzipUtils: failed to ungzip");
			return bArr;
		}
	}

	public static void main(String[] args) {
		String data = "raw data: hello world!";
		data = "{\"featureYear\":2023,\"featureMonth\":7}";
		byte[] gzipByte = gzip(data.getBytes());
		String gzipData = new String(gzipByte, StandardCharsets.UTF_8);
		logger.info("gzipData: " + gzipData);
		String ungzipData = new String(ungzip(gzipByte));
		logger.info("ungzipData: " + ungzipData);
		
		Map<String, Integer> paramMap = (Map<String, Integer>) JSONObject.parse(ungzipData);
		for (Entry<String, Integer> entry : paramMap.entrySet()) {
			logger.info("参数key：" + entry.getKey() + ", value:" + entry.getValue());
		}
		
	}
}